#include<iostream>
using namespace std;
#include<vector>
#include<queue>
class Solution {
public:
    int minReorder(int n, vector<vector<int>>& connections) {
        vector<vector<int>> go(n), back(n);
        int ans = 0;
        vector<int> check(n);
        check[0] = 1;
        for (auto& e : connections)
        {
            go[e[0]].push_back(e[1]);
            back[e[1]].push_back(e[0]);
        }
        queue<int> que;
        que.push(0);
        while (que.size())
        {
            int now = que.front();
            que.pop();
            for (auto& e : go[now])
            {
                if (check[e] == 0) {
                    que.push(e);
                    check[e] = 1;
                    ++ans;
                }
            }
            for (auto& e : back[now])
            {
                if (check[e] == 0) {
                    que.push(e);
                    check[e] = 1;
                }
            }
        }
        return ans;
    }
};